package com.uplift.common.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;

/**
 * URL匹配器，主要是针对URL通配符的处理
 * @author 王炳成
 * @version 1.0
 */
public class URLMatcher {
	private static String WILDCARD  = "*";				//通配符
	private static String WILDCARD2 = "**";				
	private static String SEPARATOR = "/";
	private static String parse(String url) throws Exception{
		String purl = url;
		StringBuffer regStr = new StringBuffer();
		//如果不以通配符开头
		//if(!StringUtils.startsWith(url, URLMatcher.WILDCARD)){
			regStr.append("^");
		//}
		purl = StringUtils.replace(purl, URLMatcher.WILDCARD2, "(.{0,})");			//多层级的
		purl = StringUtils.replace(purl, URLMatcher.WILDCARD, "([.[^/]]{0,})");		//单层的
		
		//如果以"/"结尾，则去掉
		if(StringUtils.endsWith(purl, URLMatcher.SEPARATOR)){
			purl = StringUtils.substring(purl, 0, purl.length() - 1);
		}
		regStr.append(purl);
		//如果不以通配符（1、2）结尾
		//if(!StringUtils.endsWith(url, URLMatcher.WILDCARD) && !StringUtils.endsWith(url, URLMatcher.WILDCARD2)){
			regStr.append("$");
		//}
		return regStr.toString();
	}
	/**
	 * 通过正则表达式对比URL是否符合规则
	 * @param ptargetURL
	 * @param reqURI
	 * @return boolean 
	 * @throws BaseException
	 */
	public static boolean match(String ptargetURL, String reqURI){
		boolean flag = false;
		try{
			String targetURL = StringUtils.replace(ptargetURL,"$", "\\$");
			if(StringUtils.equals(reqURI, "/") && StringUtils.equals(ptargetURL, "/")){
				flag = true;
			}else{
				String reg = parse(targetURL);
				Pattern pattern = Pattern.compile(reg);
				Matcher mcr = pattern.matcher(reqURI);
				flag = mcr.find();
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
		return flag;
	}
	public static void main(String[] args) {
		try {
			System.out.println(URLMatcher.match("/web/*.jsp","/web/jsp/a.jsp"));
			System.out.println(URLMatcher.match("/web/**.jsp","/web/jsp/a.jsp"));
			
			System.out.println(URLMatcher.match("*/web/**.jsp","res/res/web/jsp/a.jsp"));
			System.out.println(URLMatcher.match("*/web/**.jsp","res/web/jsp/a.jsp"));
			System.out.println(URLMatcher.match("*/web/**.jsp","res/web/jsp/jsp/a.jsp"));
			
			System.out.println(URLMatcher.match("*/web/*.jsp","res/web/jsp/a.jsp"));
			System.out.println(URLMatcher.match("*/web/*.jsp","res/web/a.jsp"));
			System.out.println(URLMatcher.match("*/web/*.jsp","res/res/web/a.jsp"));
			
			System.out.println(URLMatcher.match("**/web/*.jsp","res/res/web/a.jsp"));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
